package com.bikes.mileagetracker

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import com.bikes.mileagetracker.entity.UserEntity
import com.bikes.mileagetracker.service.LocationService
import com.bikes.mileagetracker.service.PersistenceImpl
import com.bikes.mileagetracker.service.PersistenceService
import com.bikes.mileagetracker.utils.ToastUtils
import com.bikes.mileagetracker.utils.androidLocationPermissionCloseAnyDecide
import com.bikes.mileagetracker.utils.androidVersionAfter6V23DecideRun
import kotlinx.android.synthetic.main.activity_main.*
import org.apache.commons.lang3.StringUtils
import java.util.*

@Suppress("UNREACHABLE_CODE")
class MainActivity : AppCompatActivity() {
    companion object {
        const val PREMISSION_REQUEST_CODE = 0x10
    }


    var persistence:PersistenceImpl = PersistenceImpl()
    var userList:ArrayList<UserEntity>? = ArrayList()
    var user: UserEntity = UserEntity()


    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        //bind service before any one use it.
        PersistenceService.bind(MileageTrackerApplication.getCurrentApplication())
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //actionBar
        supportActionBar!!.setDisplayShowHomeEnabled(true)
        supportActionBar!!.setIcon(R.drawable.ic_actionbar_icon)


        userList!!.addAll(persistence.loadUserList())
        val adapter:ArrayAdapter<UserEntity>? = ArrayAdapter(this,android.R.layout.simple_spinner_item,userList)
        vw_user_spinner.adapter = adapter

        vw_user_spinner.onItemSelectedListener = object:AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                user = adapter!!.getItem(position)
                MileageTrackerApplication.updateCurrentAccount(user)
            }
        }


        /*
        *      remove a user
        * */
        vw_rm_button.setOnClickListener{ it ->

            if(!StringUtils.isEmpty(user.id)){
                val builder = AlertDialog.Builder(this)
                        .setTitle("Remove user Information")
                        .setMessage("Please confirm to remove current user")
                        .setNegativeButton("CANCEl"){
                            dialog, which ->
                            dialog.dismiss()
                        }
                        .setPositiveButton("OK"){
                            dialog, which ->
                            persistence.removeUser(user)
                            adapter!!.remove(user)
                            adapter.notifyDataSetChanged()
                        }
                val alert = builder.create()
                alert.show()
            }else{
                ToastUtils.showToastShort("Please select the user account you want to delete!!!")
            }
        }
        vw_edit_button.setOnClickListener{
            if(!StringUtils.isEmpty(user.id)){
                val editUser: View = View.inflate(this,R.layout.layout_change_user_information,null)
                editUser.findViewById<TextView>(R.id.vw_change_name).hint = user.username
                val builder = AlertDialog.Builder(this)
                        .setTitle("Edit user Information")
                        .setView(editUser)
                        .setNegativeButton("CANCEL"){
                            dialogInterface, i ->
                            dialogInterface.dismiss()
                        }
                        .setPositiveButton("OK"){
                            dialogInterface, i ->
                            val u: UserEntity? = persistence.findUserById(user.id)
                            u?.username = editUser.findViewById<TextView>(R.id.vw_change_name).text.toString()
                            if(!u?.username.isNullOrEmpty()){
                                if (u != null) {
                                     persistence.saveUser(u)
                                }
                            }
                            adapter!!.remove(user)
                            adapter.add(u)
                            adapter.notifyDataSetChanged()
                        }
                val alert = builder.create()
                alert.show()
            }else{
                ToastUtils.showToastShort("Please select the user account you want to edit!!!")
            }
        }
        vw_add_button.setOnClickListener{
            val addUser:View = View.inflate(this,R.layout.layout_add_new_user,null)
            val builder = AlertDialog.Builder(this)
                    .setTitle("Remove user Information")
                    .setView(addUser)
                    .setNegativeButton("CANCEL"){
                        dialogInterface, i ->
                        dialogInterface.dismiss()
                    }
                    .setPositiveButton("OK"){
                        dialogInterface, i ->
                        val u = UserEntity()
                        u.username = addUser.findViewById<TextView>(R.id.vw_input_name).text.toString()
                        persistence.saveUser(u)
                        adapter!!.add(u)
                        adapter.notifyDataSetChanged()
                        ToastUtils.showToastLong("success")
                    }
            val alert = builder.create()
            alert.show()

        }

        vw_walk_frame.visibility = View.GONE

        vw_googlpmap_icon.setOnClickListener {
            val intent = Intent(this@MainActivity, MapsActivity::class.java)
            startActivity(intent)
        }
        vw_start_stop_button.setOnClickListener {
            if(!StringUtils.isEmpty(user.id)){
                androidVersionAfter6V23DecideRun{// android6 check runtime premissions
                    if (androidLocationPermissionCloseAnyDecide.decide()){
                        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), PREMISSION_REQUEST_CODE)
                    }
                }

                if(vw_start_stop_text.text.toString().equals("START")){
                    vw_start_stop_text.text = "STOP"
                    vw_walk_frame.visibility = View.VISIBLE
                    vw_walk_distance_text.setText("0")
                    LocationService.LOCATION_UPDATE_DELEGATES.clear()
                    startService(Intent(this@MainActivity, LocationService::class.java))
                    LocationService.LOCATION_UPDATE_DELEGATES.add{_,_->
                        MileageTrackerApplication.getCurrentTracking()?.also {
                            vw_walk_distance_text.text = it.miles.toString()
                        }
                    }
                }else{
                    vw_start_stop_text.text = "START"
                    vw_walk_frame.visibility = View.INVISIBLE

                    val builder = AlertDialog.Builder(this)
                            .setTitle("Confirm")
                            .setMessage("Do you really want to stop tracking?")
                            .setNegativeButton("NO"){
                                dialog, which ->
                                dialog.dismiss()
                            }
                            .setPositiveButton("YES"){
                                dialog, which ->
                                LocationService.LOCATION_UPDATE_DELEGATES.clear()

                                LocationService.CURRENT_LOCATION_SERVICE?.stop()
                                //MileageTrackerApplication.updateCurrentTracking(null)
                            }
                    val alert = builder.create()
                    alert.show()



                }
            }else{
                ToastUtils.showToastShort("Please select the user you want to operate!!!")
            }
        }

        vw_view_log_button.setOnClickListener {
            if(!StringUtils.isEmpty(user.id)){
                val intent = Intent(this@MainActivity, LogActivity::class.java)
                startActivity(intent)
            }else{
                ToastUtils.showToastShort("Please select the user you want to check!!!")
            }
        }

        vw_plot_button.setOnClickListener {

        }
        vw_statistics_button.setOnClickListener {

        }


    }
    /*
    * 刷新页面
    * */
    fun reflash(){
        finish()
        val intent = Intent(this@MainActivity, MainActivity::class.java)
        startActivity(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            PREMISSION_REQUEST_CODE ->{
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                } else {
                    // Permission Denied
                }
            }
        }
    }
}
